import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:sjx/pages/task/receive/process/task_receive_process_vm.dart';
import 'package:sjx/repository/model/task_detail_model.dart';
import 'package:sjx/repository/model/task_process_step_model.dart';
import 'package:sjx/route/route_utils.dart';
import 'package:sjx/route/routes.dart';

class ReceiveTaskProcessPage extends StatefulWidget {
  final String orderNo;
  final VoidCallback? reloadHandle;

  const ReceiveTaskProcessPage({
    Key? key,
    required this.orderNo,
    this.reloadHandle,
  }) : super(key: key);

  @override
  _ReceiveTaskProcessPageState createState() => _ReceiveTaskProcessPageState();
}

class _ReceiveTaskProcessPageState extends State<ReceiveTaskProcessPage> {
  late final ReceiveTaskProcessViewModel _viewModel;

  @override
  void initState() {
    super.initState();
    _viewModel = ReceiveTaskProcessViewModel();
    _requestData();
  }

  void _requestData() async {
    await _viewModel.requestOrderDetail(widget.orderNo);
    await _viewModel.requestOrderProcess(widget.orderNo);
    if (mounted) {
      setState(() {});
    }
  }

  void _goBack() => Navigator.pop(context);

  void _showTaskDetail() {
    RouteUtils.pushForNamed(context, RoutePath.task_detail, arguments: _viewModel.taskDetailModel?.taskNo);
  }

  void _appealTask() {
    // TODO: 跳转到申诉页
  }

  void _showSubmitContent() {
    RouteUtils.pushForNamed(context, RoutePath.task_submit_detail, arguments: {'taskNo': _viewModel.taskDetailModel?.taskNo, 'orderNo': _viewModel.taskDetailModel?.orderNo});
  }

  void _refreshData() {
    _requestData();
    widget.reloadHandle?.call();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider.value(
      value: _viewModel,
      child: Consumer<ReceiveTaskProcessViewModel>(
        builder: (context, viewModel, child) {
          final taskDetail = viewModel.taskDetailModel;
          final processSteps = viewModel.listProcess;

          if (taskDetail == null || processSteps == null) {
            return Scaffold(
              body: Center(child: CircularProgressIndicator()),
            );
          }

          return Scaffold(
            body: Stack(
              children: [
                _buildBackground(),
                CustomScrollView(
                  slivers: [
                    _buildAppBar(),
                    _buildContent(taskDetail, processSteps),
                  ],
                ),
              ],
            ),
            bottomNavigationBar: SafeArea(child: _buildActionButton(taskDetail)),
          );
        },
      ),
    );
  }

  Widget _buildActionButton(TaskDetailModel model) {
    // 根据状态确定按钮样式和行为
    final (disabled, backgroundColor) = _getButtonStyle(model.taskStatus);
    return SizedBox(
      width: double.infinity,
      child: ElevatedButton(
        style: ElevatedButton.styleFrom(
            padding: EdgeInsets.symmetric(vertical: 16.h),
            backgroundColor: backgroundColor,
            shape: BeveledRectangleBorder()
        ),
        onPressed: disabled ? null : () => _actionTask(context, model),
        child: Text(
          model.statusLabel ?? '领取任务',
          style: TextStyle(
            fontSize: 16.sp,
            color: Colors.white,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    );
  }

  void _actionTask(BuildContext context, TaskDetailModel model) {
    if (model.taskStatus == '待提交' || model.taskStatus == '已拒绝') {
      RouteUtils.pushForNamed(
        context,
        RoutePath.task_submit,
        arguments: {'taskNo': model.taskNo},
      ).then((_) {
        _refreshData();
      });
    }
  }

  // 辅助方法：根据状态返回按钮样式
  (bool, Color) _getButtonStyle(String? statusLabel) {
    switch (statusLabel) {
      case '待提交':
        return (false, Color.fromRGBO(75, 190, 151, 1));
      case '已拒绝':
        return (false, Color.fromRGBO(75, 190, 151, 1));
      default:
        return (true, Colors.grey);
    }
  }

  Widget _buildBackground() {
    return Container(
      height: 200,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [Color(0xFFFF475F), Color(0xFFFF5844)],
          begin: Alignment.topLeft,
          end: Alignment.topRight,
        ),
      ),
    );
  }

  SliverAppBar _buildAppBar() {
    return SliverAppBar(
      expandedHeight: 0,
      floating: false,
      pinned: true,
      backgroundColor: Colors.transparent,
      leading: IconButton(
        icon: Icon(Icons.arrow_back, color: Colors.white),
        onPressed: _goBack,
      ),
      title: Text('任务进程', style: TextStyle(color: Colors.white)),
      centerTitle: true,
    );
  }

  SliverToBoxAdapter _buildContent(TaskDetailModel taskDetail, List<TaskProcessStepModel> processSteps) {
    return SliverToBoxAdapter(
      child: Column(
        children: [
          _buildTaskCard(taskDetail),
          _buildProcessSteps(processSteps),
          SizedBox(height: 20), // 底部留白
        ],
      ),
    );
  }

  Widget _buildTaskCard(TaskDetailModel taskDetail) {
    return GestureDetector(
      onTap: _showTaskDetail,
      child: Card(
        margin: EdgeInsets.only(right: 16.w, left: 16.w, top: 10.h),
        child: Padding(
          padding: EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(8.r),
                    child: CachedNetworkImage(
                      imageUrl: taskDetail.publisherVartar,
                      height: 50.h,
                      width: 50.h,
                      fit: BoxFit.cover,
                      errorWidget: (context, url, error) {
                        return Image.asset(
                          'assets/images/header.png',
                          width: 120.h,
                          height: 120.h,
                          fit: BoxFit.cover,
                        );
                      },
                    ),
                  ),
                  SizedBox(width: 12),
                  Expanded(
                    child: Text(
                      taskDetail.taskTitle ?? '未知任务',
                      style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                    ),
                  ),
                  Text(
                    taskDetail.rewardAmountDisplay ?? '0',
                    style: TextStyle(
                      color: Colors.orange,
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  )
                ],
              ),
              SizedBox(height: 12),
              Text(
                '剩余${taskDetail.leftBidTime}份 | ${taskDetail.endTimeDisplay}',
                style: TextStyle(color: Colors.grey, fontSize: 12),
              ),
              SizedBox(height: 4),
              Text(
                '任务要求：在${taskDetail.bidSubmitDurationTimeDisplay}内完成',
                style: TextStyle(color: Colors.grey, fontSize: 12),
              ),
              SizedBox(height: 4),
              Text(
                '领取次数：可领取${taskDetail.bidTimesByUser}次',
                style: TextStyle(color: Colors.grey, fontSize: 12),
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildProcessSteps(List<TaskProcessStepModel> processSteps) {
    return ListView.builder(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      itemCount: processSteps.length,
      itemBuilder: (context, index) {
        return _buildProcessStep(processSteps[index], index, processSteps.length);
      },
    );
  }

  Widget _buildProcessStep(TaskProcessStepModel step, int index, int totalSteps) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 0),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Column(
            children: [
              Icon(
                index == totalSteps - 1
                    ? Icons.check_circle
                    : Icons.radio_button_unchecked,
                color: Colors.blue,
                size: 18,
              ),
              if (index < totalSteps - 1)
                Container(
                  width: 1,
                  height: step.stepComment.isNotEmpty || step.showSubmitResult ? 60 : 30,
                  color: Colors.blue,
                ),
            ],
          ),
          SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  step.stepTitle,
                  style: TextStyle(
                    fontSize: 15,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                SizedBox(height: 4),
                if (step.showSubmitResult)
                  TextButton(
                    onPressed: _showSubmitContent,
                    child: Text(
                      '点击查看提交内容',
                      style: TextStyle(
                        color: Colors.blue,
                        fontSize: 13,
                      ),
                    ),
                    style: TextButton.styleFrom(
                      padding: EdgeInsets.zero,
                      minimumSize: Size(50, 30),
                    ),
                  )
                else if (step.stepComment.isNotEmpty)
                  Text(
                    step.stepComment,
                    style: TextStyle(
                      color: step.isRefuse ? Colors.red : Colors.grey,
                      fontSize: 13,
                    ),
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }


  Widget _buildAppealButton() {
    return Positioned(
      bottom: 70,
      left: 0,
      right: 0,
      child: Container(
        color: Colors.orange[100],
        padding: EdgeInsets.symmetric(vertical: 8),
        child: TextButton(
          onPressed: _appealTask,
          child: Text(
            '多次提交都被拒？点这里向平台申诉！',
            style: TextStyle(
              color: Colors.orange[800],
              fontSize: 13,
            ),
          ),
        ),
      ),
    );
  }
}